package Servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/UserRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        // 数据库连接信息
        String jdbcURL = "jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8";
        String dbUser = "root";
        String dbPassword = "密码";

        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
            Connection connection = DriverManager.getConnection(jdbcURL, dbUser, dbPassword);

            // 检查用户名是否存在
            String checkUserQuery = "SELECT * FROM editors WHERE username = ?";
            PreparedStatement pstmt = connection.prepareStatement(checkUserQuery);
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                // 用户名已存在，重定向到注册页面并提示错误
                response.sendRedirect("register.jsp?message=usernameExists");
                rs.close();
                pstmt.close();
                connection.close();
                return;
            }

            // 插入新用户
            String insertUserQuery = "INSERT INTO editors (username, password, email) VALUES (?, ?, ?)";
            pstmt = connection.prepareStatement(insertUserQuery);
            pstmt.setString(1, username);
            pstmt.setString(2, password); // 注意：实际开发中应加密存储密码
            pstmt.setString(3, email);
            int rowsInserted = pstmt.executeUpdate();

            if (rowsInserted > 0) {
                // 注册成功，重定向到登录页面
                response.sendRedirect("login.jsp?message=success");
            } else {
                // 注册失败，重定向到注册页面并提示错误
                response.sendRedirect("register.jsp?message=fail");
            }

            // 关闭资源
            pstmt.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
            // 数据库连接失败，重定向到注册页面并提示错误
            response.sendRedirect("register.jsp?message=databaseError");
        }
    }
}